﻿NGUOIDUNG = function () {

}
NGUOIDUNG.columns = new Array("Nhóm", "Mã Người Dùng", "Đơn Vị", "Tên Người Dùng", "Email");
NGUOIDUNG.fieldText = new Array("TenNguoiDung", "Passwd", "Email");
NGUOIDUNG.MaDonVi = -1;
NGUOIDUNG.MaNhom = -1;
NGUOIDUNG.MaNguoiDung = -1;
NGUOIDUNG.arrays = new Array();
NGUOIDUNG.isInsert = 0;
NGUOIDUNG.dataTables = new Array();
var numberPage = 1;
NGUOIDUNG.isCheckUser = function (username, id) {
    var isBool = false;
    for (var i = 0; i < NGUOIDUNG.dataTables.length; i++) {
        var obj = NGUOIDUNG.dataTables[i];
        if (id != obj.MaNguoiDung && obj.TenNguoiDung.toUpperCase() == username.toUpperCase()) {
            return true;
        }
    }
    return isBool;
}

NGUOIDUNG.isEmail = function (email, id) {
    var isBool = false;
    for (var i = 0; i < NGUOIDUNG.dataTables.length; i++) {
        var obj = NGUOIDUNG.dataTables[i];
        if (id != obj.MaNguoiDung && obj.Email.toUpperCase() == email.toUpperCase()) {
            return true;
        }
    }
    return isBool;
}

NGUOIDUNG.Insert = function () {
    var serviceUrl = Constants.service + "insertTblNguoiDungs";
    Constants.Required(NGUOIDUNG.arrays);
    if (Constants.OnSubmit(NGUOIDUNG.arrays) == false) {
        return false;
    }
    var tenNguoiDung = $("#TenNguoiDung").val();
    var index = tenNguoiDung.indexOf(" ");
    if (index != -1) {
        $("#ErrTenNguoiDung").html("Tên người dùng không được có khoảng trắng");
        return false;
    }
    var username = $("#TenNguoiDung").val();
    var email = $("#Email").val();
    var id = parseInt($("#MaNguoiDung").val());
    if (NGUOIDUNG.isCheckUser(username, id) == true) {
        $("#ErrTenNguoiDung").html("Tên người dùng đã tồn tại");
        $("#TenNguoiDung").focus();
        return false;
    }
    if (NGUOIDUNG.isCheckUser(email, id) == true) {
        $("#Email").html("Email đã tồn tại");
        $("#ErrEmail").focus();
        return false;
    }
    var data = {
        MaNhom: $("#MaNhom").val(),
        MaNguoiDung: $("#MaNguoiDung").val(),
        MaDonVi: $("#MaDonVi").val(),
        TenNguoiDung: username,
        Passwd: $("#Passwd").val(),
        Email: email,
        DaXoa: false
    };
    var json = JSON.stringify({ item: data });
    $.ajax({
        type: "Post",
        url: serviceUrl, // Location of the service
        data: json, //Data sent to server
        contentType: "application/json", // content type sent to server
        dataType: "json", //Expected data format from server
        cache: false,
        success: function (msg) {
            NGUOIDUNG.GetData();
            Constants.Cancel();
        },
        error: function (err) {
            // When Service call fails
        }
    });
}

NGUOIDUNG.Init = function () {
    NGUOIDUNG.arrays = new Array();
    var obj;
    obj = new CheckField("TenNguoiDung", 1, "ErrTenNguoiDung");
    NGUOIDUNG.Add(obj);
    obj = new CheckField("Passwd", 1, "ErrPasswd");
    NGUOIDUNG.Add(obj);
    obj = new CheckField("Email", 3, "ErrEmail");
    NGUOIDUNG.Add(obj);
}

NGUOIDUNG.Add = function (obj) {
    if (NGUOIDUNG.arrays.contains(obj) == false) {
        NGUOIDUNG.arrays.push(obj);
    }
}

NGUOIDUNG.Delete = function (id) {    
    var data = {
        MaNguoiDung : id
    };
    var json = JSON.stringify({ item: data });
    a = confirm(Constants.messDelete);
    if (a == false) {
        return;
    }
    var serviceUrl = Constants.service + "deleteTblNguoiDungs";
    $.ajax({
        type: "Post",
        url: serviceUrl, // Location of the service
        data: json, //Data sent to server
        contentType: "application/json", // content type sent to server
        dataType: "json", //Expected data format from server
        cache: false,
        success: function (data) {
            NGUOIDUNG.GetData();
        },
        error: function (err) {
            // When Service call fails
        }
    });
}

NGUOIDUNG.UpdateItem = function () {
    var serviceUrl = Constants.service + "updateTblNguoiDungs";
    Constants.Required(NGUOIDUNG.arrays);
    if (Constants.OnSubmit(NGUOIDUNG.arrays) == false) {
        return false;
    }
    var tenNguoiDung = $("#TenNguoiDung").val();
    var index = tenNguoiDung.indexOf(" ");
    if (index != -1) {
        $("#TenNguoiDung").html("Tên người dùng không được có khoảng trắng");
        return false;
    }
    var username = $("#TenNguoiDung").val();
    var email = $("#Email").val();
    var id = parseInt($("#MaNguoiDung").val());
    if (NGUOIDUNG.isCheckUser(username, id) == true) {
        $("#ErrTenNguoiDung").html("Tên người dùng đã tồn tại");
        $("#TenNguoiDung").focus();
        return false;
    }
    if (NGUOIDUNG.isCheckUser(email, id) == true) {
        $("#Email").html("Email đã tồn tại");
        $("#ErrEmail").focus();
        return false;
    }
    var data = {
        MaNhom: $("#MaNhom").val(),
        MaNguoiDung: $("#MaNguoiDung").val(),
        MaDonVi: $("#MaDonVi").val(),
        TenNguoiDung: $("#TenNguoiDung").val(),
        Passwd: $("#Passwd").val(),
        Email: $("#Email").val(),
        DaXoa: false
    };
    var json = JSON.stringify({ item: data });
    $.ajax({
        type: "Post",
        url: serviceUrl, // Location of the service
        data: json, //Data sent to server
        contentType: "application/json", // content type sent to server
        dataType: "json", //Expected data format from server
        cache: false,
        success: function (msg) {
            NGUOIDUNG.GetData();
            Constants.Cancel();
        },
        error: function (err) {
            // When Service call fails
        }
    });
}

NGUOIDUNG.CreateTable = function (r, nbpage, data) {
    var myTable = NGUOIDUNG.TitleColumns(NGUOIDUNG.columns);
    myTable += NGUOIDUNG.DataColumnsOftr(data, r, nbpage);
    myTable += "</table>";
    $("#div_list").children().remove();
    $("#div_list").append(myTable);
    $("#div_content").show();
}

NGUOIDUNG.GetData = function () {
    var serviceUrl = Constants.service + "getAllTblNguoiDungs";
    var data = { url: window.location.host };
    var json = JSON.stringify({ item: data });
    NGUOIDUNG.isInsert = 0;
    NGUOIDUNG.dataTables = new Array();
    $.ajax({
        type: "Post",
        url: serviceUrl, // Location of the service
        data: json, //Data sent to server
        contentType: "application/json", // content type sent to server
        dataType: "json", //Expected data format from server
        cache: false,
        success: function (msg) {
            var results = msg.getAllTblNguoiDungsResult;
            NGUOIDUNG.dataTables = results;
            NGUOIDUNG.CreateTable(Constants.rows, numberPage, NGUOIDUNG.dataTables);
        },
        error: function (err) {
            // When Service call fails
        }
    });
}

NGUOIDUNG.TitleColumns = function (_columns) {
    var myColumns = "<table class=\"rounded-corner\">";
    myColumns += "<thead><tr>";
    for (var i = 0; i < _columns.length; i++) {
        myColumns += "<th class=\"rounded\" scope=\"col\">" + _columns[i] + "</th>";
    }
    myColumns += "<th class=\"rounded\" scope=\"col\">Edit</th>";
    myColumns += "<th class=\"rounded-q4\" scope=\"col\">Delete</th>";
    myColumns += "</tr></thead>";
    var n = _columns.length + 1;
    myColumns += "<tfoot><tr><td class=\"rounded-foot-left\" colspan=\"" + n + "\"><em> </em></td>";
    myColumns += "<td class=\"rounded-foot-right\">&nbsp;</td>";
    myColumns += "</tr></tfoot>";
    return myColumns;
}

NGUOIDUNG.DataColumnsOftr = function (data, rs, _numberPage) {
    var myDataColumns = "<tbody>";
    var n = data.length;
    var j = (_numberPage - 1) * rs;
    var r = rs;
    for (var i = j; i < r && i < n; i++) {
        var id = data[i].MaNguoiDung;
        var tennguoidung = data[i].TenNguoiDung; //admin
        if (tennguoidung == "admin")
            continue;
        myDataColumns += "<tr onclick='return NGUOIDUNG.OnClick(" + id + ")'" + " id=\"" + id + "\">";
        myDataColumns += "<td>" + data[i].TenNhom + "</td>"
        myDataColumns += "<td>" + data[i].MaNguoiDung + "</td>"
        myDataColumns += "<td>" + data[i].TenDonVi + "</td>"
        myDataColumns += "<td>" + data[i].TenNguoiDung + "</td>"        
        myDataColumns += "<td>" + data[i].Email + "</td>"
        myDataColumns += "<td><img onclick='return NGUOIDUNG.EditItem(" + id + ")' border=\"0\" title=\"\" alt=\"" + id + "\" src=\"images/user_edit.png\"></td>";
        myDataColumns += "<td><a class=\"ask\" ><img onclick='return NGUOIDUNG.Delete(" + id + ")' border=\"0\" title=\"\" alt=\"" + id + "\" src=\"images/trash.png\"></a></td>";
    }
    myDataColumns += "</tbody>";
    return myDataColumns;
}

NGUOIDUNG.OnClick = function (id) {
    NGUOIDUNG.MaNguoiDung = id;
    $(".active").removeClass();
    $("#" + id).addClass("active");
    return false;
}

NGUOIDUNG.OnClickEdit = function () {
    if (NGUOIDUNG.MaNguoiDung == -1) {
        alert(Constants.selectEdit);
    }
    else
        NGUOIDUNG.EditItem(NGUOIDUNG.MaNguoiDung);
}

NGUOIDUNG.OnClickDelete = function () {
    if (NGUOIDUNG.MaNguoiDung == -1) {
        alert(Constants.selectDelete);
    }
    else
        NGUOIDUNG.Delete(NGUOIDUNG.MaNguoiDung);
}

NGUOIDUNG.EditItem = function (id) {        
    var temp_item = "Modules/nd/Edit";   
    $("#dialog").empty();
    $.ajax({
        url: temp_item + ".htm",
        success: function (data) {
            $('#dialog').append(data);
            $("#dialog").dialog("open");
            $("#dialog").dialog({ title: "Sửa" });
            Constants.GetNhomNguoiDung("MaNhom");
            Constants.GetDonVi("MaDonVi");
            NGUOIDUNG.GetItem(id);            
        }
    });
}


NGUOIDUNG.GetItem = function (id) {

    var serviceUrl = Constants.service + "getItemByIdTblNguoiDung";
    var data = { MaNguoiDung : id };
    var json = JSON.stringify({ item: data });
    NGUOIDUNG.MaDonVi = -1;
    NGUOIDUNG.MaNhom = -1;
    $.ajax({
        type: "Post",
        url: serviceUrl, // Location of the service
        data: json, //Data sent to server
        contentType: "application/json", // content type sent to server
        dataType: "json", //Expected data format from server
        cache: false,
        success: function (msg) {
            var result = msg.getItemByIdTblNguoiDungResult;
            if (result != null && result != undefined) {
                NGUOIDUNG.MaDonVi = result.MaDonVi;
                NGUOIDUNG.MaNhom = result.MaNguoiDung;
                $("#MaNhom").val(result.MaNhom);
                $("#MaNguoiDung").val(result.MaNguoiDung);
                $("#MaDonVi").val(result.MaDonVi);
                $("#TenNguoiDung").val(result.TenNguoiDung);
                $("#Passwd").val(result.Passwd);
                $("#Email").val(result.Email);
            }
        },
        error: function (err) {
            // When Service call fails
        }
    });
}

NGUOIDUNG.Clear = function () {
    Constants.clearAll(NGUOIDUNG.fieldText);
}

NGUOIDUNG.AddNewItem = function () {
    var temp_item = "Modules/nd/AddNew";
    NGUOIDUNG.isInsert = 1;
    $("#dialog").empty();
    $.ajax({
        url: temp_item + ".htm",
        success: function (data) {
            $('#dialog').append(data);
            $("#dialog").dialog("open");
            $("#dialog").dialog({ title: "Thêm Mới" });
            NGUOIDUNG.getMa();
            Constants.GetNhomNguoiDung("MaNhom");
            Constants.GetDonVi("MaDonVi");
        }
    });
}

NGUOIDUNG.Enter = function () {
    $("#TenNguoiDung").keypress(function (event) {
        if (event.keyCode == 13) {
            $("#Passwd").focus();
            event.preventDefault();
        }
    });
    $("#Passwd").keypress(function (event) {
        if (event.keyCode == 13) {
            $("#Email").focus();
            event.preventDefault();
        }
    });

    $("#Email").keypress(function (event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            if (NGUOIDUNG.isInsert == 1) {
                NGUOIDUNG.Insert();
            }
            else {
                NGUOIDUNG.UpdateItem();
            }
        }
    });
}

NGUOIDUNG.getMa = function () {
    var serviceUrl = Constants.service + "getMaTblNguoiDung";
    $.ajax({
        type: "Post",
        url: serviceUrl,
        contentType: "application/json",
        dataType: "json",
        cache: false,
        success: function (msg) {
            var result = msg.getMaTblNguoiDungResult;
            if (result != null && result != null) {
                $("#MaNguoiDung").val(result);
            }
        }
    });
}

NGUOIDUNG.Search = function () {
    var serviceUrl = Constants.service + "getFindTblNguoiDungs";
    var data = {
        value: $("#search").val()
    };
    var json = JSON.stringify({ item: data });
    $.ajax({
        type: "Post",
        url: serviceUrl,
        data: json,        
        contentType: "application/json",
        dataType: "json",
        cache: false,
        success: function (msg) {
            var results = msg.getFindTblNguoiDungsResult;
            if (results != null && results.length > 0) {
                NGUOIDUNG.CreateTable(Constants.rows, numberPage, results);
            }
            else {
                $("#div_list").children().remove();
                $("#div_list").html(Constants.find);
            }
        }
    });
}

$(document).ready(function () {
    NGUOIDUNG.GetData();
    NGUOIDUNG.Init();  
    $("#search").keypress(function (event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            NGUOIDUNG.Search();
        }
    });
    $("#search_on").click(function (event) {
        event.preventDefault();
        NGUOIDUNG.Search();
    });

});